package org.data;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Clean0 {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        //1 获取job对象
        Configuration conf = new Configuration();
        conf.set("mapred.textoutputformat.separator", ",");
        conf.set("mapred.textoutputformat.ignoreseparator", "true");
        Job job = Job.getInstance(conf);

        //2 关联Driver类
        job.setJarByClass(Clean0.class);

        //3 关联Mapper和Reducer类
        job.setMapperClass(Clean0Mapper.class);
        job.setReducerClass(Clean0Reducer.class);

        //4 设置Map的输入输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        //5	设置最终的输入输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        //6	设置输入输出路径
        FileInputFormat.setInputPaths(job, new Path("D:\\data\\Taxi_Trips.csv"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\data\\out0"));

        //7 提交job
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);
    }
}


class Clean0Mapper extends Mapper<LongWritable,Text,Text,Text> {

    private Text outK = new Text();
    private Text outV =  new Text();


    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] csvComments = value.toString().split(",");
        if(!csvComments[16].equals("") || !csvComments[14].equals("")){
            outK.set(csvComments[16]);
            outV.set(csvComments[14]);
            context.write(outK,outV);
        }
    }

}

class Clean0Reducer extends Reducer<Text, Text, Text, Text> {

    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        Text content=new Text();
        for (Text value:values){
            content.set(value);
            context.write(key,content);
        }
    }

}

